package util

import (
	"strconv"
	"time"
	"zimuzu_cvn_web_api/config"
	. "zimuzu_cvn_web_api/pkg/e"
	"zimuzu_cvn_web_api/pkg/errno"
)

var (
	appSecretKey   = "m0GseN2RwbUM9j40feJ6"
	appSignNamePrx = "AppCreateSingV"
	appCommand     = map[string]func(query, author string) string{
		"AppCreateSingV1": AppCreateSingV1,
		"AppCreateSingV2": AppCreateSingV2,
	}
)

//校验签名
func AppCheckSign(bodyStr, author, sign string) (ok bool, err error) {
	var (
		com     string
		nowTime = time.Now().Unix()
	)
	params := ParsePostForm(bodyStr)
	query := SortParams(params)
	sv := params["sv"]
	t, err := strconv.ParseInt(params["t"], 10, 64)
	if nowTime-t > SignExpire {
		err = errno.SignExpire
		return false, err
	} else if t-nowTime > SignExpire {
		err = errno.SignInvalid
		return false, err
	}
	com = appSignNamePrx + sv
	verify := AppCall(com, query, author)
	if verify == "" {
		err = errno.ParamsError
		return false, err
	}
	if sign != verify {
		err = errno.SignError
		return false, err
	}
	return true, nil
}

//动态调用函数
func AppCall(com, query, author string) string {
	if function, ok := appCommand[com]; ok {
		return function(query, author)
	}
	return ""
}

//生成签名-1
func AppCreateSingV1(query, author string) (s string) {
	s = Sha1Str(config.C.Keys.AppAccessKey + Sha1Str(query) + appSecretKey + Sha1Str(author))
	return s
}

//生成签名-2
func AppCreateSingV2(query, author string) (s string) {
	s = Sha1Str(Sha1Str(config.C.Keys.AppAccessKey) + Sha1Str(query) + Sha1Str(appSecretKey) + Sha1Str(author))
	return s
}
